#include "commu.h"
#include <stdio.h>
#include <string.h>
#include "relay.h"
#include "cJSON.h"
#include "main.h"
struct COMM comm;

const CmdObj cmdObj[CMD_NUM] = {
	{Cmd_Device_Get_Info, 		"productInfo"},
	{Cmd_Device_Register, 		"reg"},
	{Cmd_Device_UnRegister, 	"unreg"},
	{Cmd_Device_Reset, 			"reset"},
	{Cmd_Device_Factory, 		"factory"},
	{Cmd_Device_Ctrl, 			"ctrl"},
	{Cmd_Device_Get_Status, 	"status"},
	{Cmd_Device_Upload, 		"status"},
	{Cmd_Device_Set_Config, 	"set"},
	{Cmd_Device_Get_Config, 	"get"},
};

static const uint16_t OTA_Crc16InitTable[256] ={
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
};

OTAObj otaObj;

uint8_t dmaCh2Buf[COMM_BUFFSIZE];

static uint16_t OTA_CRC16_GEN_Cal(uint8_t *pData, uint16_t len);

void comm_uart_init(void)
{
	/* 开启时钟 */
	rcu_periph_clock_enable(RCU_GPIOA);
	rcu_periph_clock_enable(RCU_GPIOB);
	rcu_periph_clock_enable(RCU_AF);
	gpio_pin_remap_config(GPIO_USART0_REMAP,ENABLE);
	rcu_periph_clock_enable(RCU_USART0);
	rcu_periph_clock_enable(RCU_DMA0);
	/* USART_GPIO配置 */
	gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_6);
	gpio_init(GPIOB, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_7);
	/* USART配置 */
	usart_baudrate_set(USART0, 115200);
	usart_parity_config(USART0, USART_PM_NONE);
	usart_word_length_set(USART0, USART_WL_8BIT);
	usart_stop_bit_set(USART0, USART_STB_1BIT);
	usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
	usart_receive_config(USART0, USART_RECEIVE_ENABLE);
	nvic_irq_enable(USART0_IRQn, 2, 0);
	usart_interrupt_enable(USART0, USART_INT_IDLE);
	usart_dma_receive_config(USART0, USART_RECEIVE_DMA_ENABLE);
	usart_enable(USART0);
	/* DMA配置 */
	dma_parameter_struct dmaInitStruct;
	dmaInitStruct.periph_addr = (uint32_t)(&USART_DATA(USART0));
	dmaInitStruct.periph_width = DMA_PERIPHERAL_WIDTH_8BIT;
	dmaInitStruct.memory_addr = (uint32_t)dmaCh2Buf;
	dmaInitStruct.memory_width = DMA_PERIPHERAL_WIDTH_8BIT;
	dmaInitStruct.number = sizeof(dmaCh2Buf);
	dmaInitStruct.priority = DMA_PRIORITY_HIGH;
	dmaInitStruct.periph_inc = DMA_PERIPH_INCREASE_DISABLE;
	dmaInitStruct.memory_inc = DMA_MEMORY_INCREASE_ENABLE;
	dmaInitStruct.direction = DMA_PERIPHERAL_TO_MEMORY;
	dma_init(DMA0, DMA_CH4, &dmaInitStruct);
	dma_circulation_disable(DMA0, DMA_CH4);
	dma_memory_to_memory_disable(DMA0, DMA_CH4);
	dma_channel_enable(DMA0, DMA_CH4);
}

void comm_send_bytes(uint8_t *buf, uint16_t len)
{
	while(len--)
	{
		usart_data_transmit(USART0, *buf++);
		/* 等待发送完毕 */
		while(usart_flag_get(USART0, USART_FLAG_TC) == RESET);
	}
}

uint8_t cal_crc_sum(uint8_t *buf, uint16_t len)
{
	uint8_t crc = 0;
	for(uint16_t i = 0; i < len; i++)
	{
		crc += buf[i];
	}
	return crc;
}
__attribute__((weak)) void comm_receiver_callback(uint8_t *buf, uint16_t len)
{
	uint8_t  frameHead[2];
	uint8_t  type;		/* protocol type */
	uint16_t sn;		/* Serial Number */
	uint16_t dataLen;
	uint8_t  data[COMM_BUFFSIZE - 8];
	uint8_t  sendBuf[COMM_BUFFSIZE];
	uint16_t sendLen = 0;
	uint8_t  *pData;
	uint8_t protocolCmd;
	cJSON *cjson_tx = NULL;
	cJSON *cjson_rx = NULL;
	cJSON *cjson_cmd = NULL;
	cJSON *cjson_data = NULL;
	cJSON *cjson_product = NULL;
	cJSON *cjson_vendor = NULL;
	cJSON *cjson_aei = NULL;
	cJSON *cjson_rsi = NULL;
	cJSON *cjson_arrItem = NULL;
	uint8_t cjson_arrSize;
	
	memset(data, 0, sizeof(data));
	
	memcpy(frameHead, &buf[0], 2);
	type = buf[2];
	sn = buf[3] | (buf[4] << 8);
	dataLen = buf[5] | (buf[6] << 8);
	memcpy(data, &buf[7], dataLen);
	/* 帧头校验 */
	if(frameHead[0] == 0xAA && frameHead[1] == 0xBB)
	{
		/* crc校验 */
		if(cal_crc_sum(buf, len - 1) == buf[len - 1])
		{
			/* plcp 透传协议(josn格式) */
			if(type == 0x01)
			{
				/* 解析整段cJSON数据 */
    			cjson_rx = cJSON_Parse((const char *)data);
				if(cjson_rx == NULL)
				{
					return ;
				}
				cjson_cmd = cJSON_GetObjectItem(cjson_rx, "cmd");

				/* 判断是哪个指令 */
				for (protocolCmd = 0; protocolCmd < CMD_NUM; protocolCmd++)
				{
					if (strcmp((const char *)cjson_cmd->valuestring, (const char *)cmdObj[protocolCmd].name) == 0)
					{
						break;
					}
				}

				if(protocolCmd >= CMD_NUM)
				{
					/* 收到PLC应答信号 */

					cJSON_Delete(cjson_rx);
					return;
				}

				sendBuf[sendLen++] = 0xAA;
				sendBuf[sendLen++] = 0xBB;
				sendBuf[sendLen++] = 0x01;
				sendBuf[sendLen++] = sn & 0xFF;
				sendBuf[sendLen++] = sn >> 8;

				/* 针对具体指令进行处理 */
				switch(protocolCmd)
				{
					case Cmd_Device_Get_Info:
					{
						/* 构建数据内容 */
						cjson_tx = cJSON_CreateObject();
						cjson_data = cJSON_CreateObject();
						cjson_product = cJSON_CreateObject();
						cjson_vendor = cJSON_CreateObject();
						cJSON_AddStringToObject(cjson_tx, "cmd", "productInfo");
						cJSON_AddItemToObject(cjson_tx, "data", cjson_data);						
						cJSON_AddItemToObject(cjson_data, "product", cjson_product);						
						cJSON_AddStringToObject(cjson_product, "name", 	"mx-plc-4key");
						cJSON_AddStringToObject(cjson_product, "type", 	"4-switch-panel");
						cJSON_AddStringToObject(cjson_product, "model", "4key");
						cJSON_AddStringToObject(cjson_product, "pid", 	"9pahxqsbbnjucnuq");
						cJSON_AddStringToObject(cjson_product, "ver", 	SOFT_VERSION);
						cJSON_AddItemToObject(cjson_product, "vendor", cjson_vendor);
						cJSON_AddStringToObject(cjson_vendor, "name", "mx");
						
						pData = (uint8_t *)cJSON_Print(cjson_tx);
						dataLen = strlen((const char *)pData);
						sendBuf[sendLen++] = dataLen & 0xFF;
						sendBuf[sendLen++] = dataLen >> 8;
						memcpy(&sendBuf[sendLen], pData, dataLen);
						sendLen += dataLen;
						/* 回收堆空间 */
						cJSON_Delete(cjson_tx);
						cJSON_Delete(cjson_rx);
						cJSON_free(pData);
					}
					break;
					case Cmd_Device_Register:
					{
						/* 已注册 */
						unRegisterHint = 0;
						/* 回收堆空间 */
						cJSON_Delete(cjson_rx);
						pData = NULL;
						dataLen = 0;
						sendBuf[sendLen++] = dataLen & 0xFF;
						sendBuf[sendLen++] = dataLen >> 8;
					}
					break;
					case Cmd_Device_UnRegister:
					{
						/* 未注册 */
						unRegisterHint = 1;
						/* 回收堆空间 */
						cJSON_Delete(cjson_rx);
						pData = NULL;
						dataLen = 0;
						sendBuf[sendLen++] = dataLen & 0xFF;
						sendBuf[sendLen++] = dataLen >> 8;
					}
					break;
					case Cmd_Device_Reset:
					{
						NVIC_SystemReset();
						/* 回收堆空间 */
						cJSON_Delete(cjson_rx);
						pData = NULL;
						dataLen = 0;
						sendBuf[sendLen++] = dataLen & 0xFF;
						sendBuf[sendLen++] = dataLen >> 8;
					}
					break;
					case Cmd_Device_Factory:
					{
						system_factory();
						/* 回收堆空间 */
						cJSON_Delete(cjson_rx);
						pData = NULL;
						dataLen = 0;
						sendBuf[sendLen++] = dataLen & 0xFF;
						sendBuf[sendLen++] = dataLen >> 8;
					}
					break;
					case Cmd_Device_Ctrl:
					{
						/* 控制对象 */
						cjson_aei = cJSON_GetObjectItem(cjson_rx, "aei");
						/* 控制指令 */
						cjson_rsi = cJSON_GetObjectItem(cjson_rx, "rsi");
						/* 控制参数 */
						cjson_data = cJSON_GetObjectItem(cjson_rx, "data");

						/* 下位机动作函数调用 */
						if(strcmp((const char *)cjson_rsi->valuestring, "_on") == 0)
						{
							relay_set(cjson_aei->valueint - 1, 1);
							led_set(cjson_aei->valueint - 1, 1);
						}
						else if(strcmp((const char *)cjson_rsi->valuestring, "_off") == 0)
						{
							relay_set(cjson_aei->valueint - 1, 0);
							led_set(cjson_aei->valueint - 1, 0);
						}
						/* 背光控制 */
						if(backLightEn)
						{
							if(get_led_state(cjson_aei->valueint - 1))
							{
								led_set(cjson_aei->valueint - 1 + 8, 0);
							}
							else
							{
								led_set(cjson_aei->valueint - 1 + 8, 1);
							}
						}
						else
						{
							led_set(cjson_aei->valueint - 1 + 8, 0);
						}
						
						/* 回收堆空间 */
						cJSON_Delete(cjson_rx);
						pData = NULL;
						dataLen = 0;
						sendBuf[sendLen++] = dataLen & 0xFF;
						sendBuf[sendLen++] = dataLen >> 8;
					}
					break;
					case Cmd_Device_Get_Status:
					{
						/* 控制对象 */
						cjson_aei = cJSON_GetObjectItem(cjson_rx, "aei");
						/* 构建数据内容 */
						cjson_tx = cJSON_CreateObject();
						cJSON_AddStringToObject(cjson_tx, "cmd", 	"status");
						if(cjson_aei->valueint < 1 || cjson_aei->valueint > 199)
						{
							/* 不存在，则默认为1 */
							cjson_aei->valueint = 1;
						}
						cJSON_AddNumberToObject(cjson_tx, "aei", 	cjson_aei->valueint);
						cJSON_AddStringToObject(cjson_tx, "rsi", 	"_state");
						/* 获取设备状态 */
						//此处调用接口函数
						cjson_data = cJSON_CreateObject();
						cJSON_AddItemToObject(cjson_tx, "data", cjson_data);
						if(get_relay_state(cjson_aei->valueint) != 0)
						{
							cJSON_AddStringToObject(cjson_data, "id", "_on");
							cJSON_AddStringToObject(cjson_data, "name", "switch");
							cJSON_AddStringToObject(cjson_data, "data", "1");
						}
						else
						{
							cJSON_AddStringToObject(cjson_data, "id", "_off");
							cJSON_AddStringToObject(cjson_data, "name", "switch");
							cJSON_AddStringToObject(cjson_data, "data", "0");
						}

						pData = (uint8_t *)cJSON_Print(cjson_tx);
						dataLen = strlen((const char *)pData);
						sendBuf[sendLen++] = dataLen & 0xFF;
						sendBuf[sendLen++] = dataLen >> 8;
						memcpy(&sendBuf[sendLen], pData, dataLen);
						sendLen += dataLen;

						/* 回收堆空间 */
						cJSON_Delete(cjson_tx);
						cJSON_Delete(cjson_rx);
						cJSON_free(pData);
					}
					break;
					case Cmd_Device_Upload:
					{
						/* 此为下位机主动上传指令 */
					}
					break;
					case Cmd_Device_Set_Config:
					{
						cjson_rsi = cJSON_GetObjectItem(cjson_rx, "rsi");
						cjson_data = cJSON_GetObjectItem(cjson_rx, "data");
						if(strcmp((const char *)cjson_rsi->valuestring, "_config") == 0)
						{
							if(strcmp((const char *)cjson_data->child->string, "bkMode") == 0)
							{
								/* 开启 */
								if(strcmp((const char *)cjson_data->child->valuestring, "open") == 0)
								{
									backLightEn = 1;
								}
								/* 关闭 */
								else if(strcmp((const char *)cjson_data->child->valuestring, "close") == 0)
								{
									backLightEn = 0;
								}
								/* 自动 */
								else if(strcmp((const char *)cjson_data->child->valuestring, "auto") == 0)
								{
									backLightEn = 2;
								}
								eeprom_write_one_byte(EEPROM_ADDR_BACKLIGHT_EN, backLightEn);
							}
							else if(strcmp((const char *)cjson_data->child->string, "key-1-report") == 0)
							{
								/* 按键状态上传 */
								if(cjson_data->child->valueint != 0)
								{
									keyxUpLoadEn[1 - 1] = 1;
								}
								/* 按键状态不上传 */
								else
								{
									keyxUpLoadEn[1 - 1] = 0;
								}
								eeprom_write_one_byte(EEPROM_ADDR_KEY1_UPLOAD_EN, keyxUpLoadEn[1 - 1]);
							}
							else if(strcmp((const char *)cjson_data->child->string, "key-2-report") == 0)
							{
								/* 按键状态上传 */
								if(cjson_data->child->valueint != 0)
								{
									keyxUpLoadEn[2 - 1] = 1;
								}
								/* 按键状态不上传 */
								else
								{
									keyxUpLoadEn[2 - 1] = 0;
								}
								eeprom_write_one_byte(EEPROM_ADDR_KEY2_UPLOAD_EN, keyxUpLoadEn[2 - 1]);
							}
							else if(strcmp((const char *)cjson_data->child->string, "key-3-report") == 0)
							{
								/* 按键状态上传 */
								if(cjson_data->child->valueint != 0)
								{
									keyxUpLoadEn[3 - 1] = 1;
								}
								/* 按键状态不上传 */
								else
								{
									keyxUpLoadEn[3 - 1] = 0;
								}
								eeprom_write_one_byte(EEPROM_ADDR_KEY3_UPLOAD_EN, keyxUpLoadEn[3 - 1]);
							}
							else if(strcmp((const char *)cjson_data->child->string, "key-4-report") == 0)
							{
								/* 按键状态上传 */
								if(cjson_data->child->valueint != 0)
								{
									keyxUpLoadEn[4 - 1] = 1;
								}
								/* 按键状态不上传 */
								else
								{
									keyxUpLoadEn[4 - 1] = 0;
								}
								eeprom_write_one_byte(EEPROM_ADDR_KEY4_UPLOAD_EN, keyxUpLoadEn[4 - 1]);
							}
						}
						/* 回收堆空间 */
						cJSON_Delete(cjson_rx);
						cJSON_Delete(cjson_tx);
						/* 数据内容为null */
						pData = NULL;
						dataLen = 0;
						sendBuf[sendLen++] = dataLen & 0xFF;
						sendBuf[sendLen++] = dataLen >> 8;
					}
					break;
					case Cmd_Device_Get_Config:
					{
						cjson_rsi = cJSON_GetObjectItem(cjson_rx, "rsi");
						cjson_data = cJSON_GetObjectItem(cjson_rx, "data");
						cjson_arrSize = cJSON_GetArraySize(cjson_data);
						if(strcmp((const char *)cjson_rsi->valuestring, "_config") == 0)
						{
							cjson_tx = cJSON_CreateObject();
							cJSON_AddStringToObject(cjson_tx, "cmd", "get");
							cJSON_AddStringToObject(cjson_tx, "rsi", "_config");
							cjson_data = cJSON_CreateObject();
							cJSON_AddItemToObject(cjson_tx, "data", cjson_data);
							if(cjson_arrSize != 0)
							{
								cjson_tx = cJSON_CreateObject();
								for(uint8_t i = 0; i < cjson_arrSize; i++)
								{
									cjson_arrItem = cJSON_GetArrayItem(cjson_data, i);
									if(strcmp((const char *)cjson_arrItem->string, "bkMode") == 0)
									{
										/* 背光配置 */
										if(backLightEn == 0)
										{
											cJSON_AddStringToObject(cjson_data, "bkMode", "close");
										}
										else if(backLightEn == 1)
										{
											cJSON_AddStringToObject(cjson_data, "bkMode", "open");
										}
										else if(backLightEn == 2)
										{
											cJSON_AddStringToObject(cjson_data, "bkMode", "auto");
										}
									}
									else if(strcmp((const char *)cjson_arrItem->string, "key-1-report") == 0)
									{
										if(keyxUpLoadEn[1 - 1] != 0)
										{
											cJSON_AddNumberToObject(cjson_data, "key-1-report", 1);
										}
										else
										{
											cJSON_AddNumberToObject(cjson_data, "key-1-report", 0);
										}
									}
									else if(strcmp((const char *)cjson_arrItem->string, "key-2-report") == 0)
									{
										if(keyxUpLoadEn[2 - 1] != 0)
										{
											cJSON_AddNumberToObject(cjson_data, "key-2-report", 1);
										}
										else
										{
											cJSON_AddNumberToObject(cjson_data, "key-2-report", 0);
										}
									}
									else if(strcmp((const char *)cjson_arrItem->string, "key-3-report") == 0)
									{
										if(keyxUpLoadEn[3 - 1] != 0)
										{
											cJSON_AddNumberToObject(cjson_data, "key-3-report", 1);
										}
										else
										{
											cJSON_AddNumberToObject(cjson_data, "key-3-report", 0);
										}
									}
									else if(strcmp((const char *)cjson_arrItem->string, "key-4-report") == 0)
									{
										if(keyxUpLoadEn[4 - 1] != 0)
										{
											cJSON_AddNumberToObject(cjson_data, "key-4-report", 1);
										}
										else
										{
											cJSON_AddNumberToObject(cjson_data, "key-4-report", 0);
										}
									}
								}
							}
							else
							{
								/* 上传所有配置 */
								if(backLightEn == 0)
								{
									cJSON_AddStringToObject(cjson_data, "bkMode", "close");
								}
								else if(backLightEn == 1)
								{
									cJSON_AddStringToObject(cjson_data, "bkMode", "open");
								}
								else if(backLightEn == 2)
								{
									cJSON_AddStringToObject(cjson_data, "bkMode", "auto");
								}
								if(keyxUpLoadEn[1 - 1] != 0)
								{
									cJSON_AddNumberToObject(cjson_data, "key-1-report", 1);
								}
								else
								{
									cJSON_AddNumberToObject(cjson_data, "key-1-report", 0);
								}
								if(keyxUpLoadEn[2 - 1] != 0)
								{
									cJSON_AddNumberToObject(cjson_data, "key-2-report", 1);
								}
								else
								{
									cJSON_AddNumberToObject(cjson_data, "key-2-report", 0);
								}
								if(keyxUpLoadEn[3 - 1] != 0)
								{
									cJSON_AddNumberToObject(cjson_data, "key-3-report", 1);
								}
								else
								{
									cJSON_AddNumberToObject(cjson_data, "key-3-report", 0);
								}
								if(keyxUpLoadEn[4 - 1] != 0)
								{
									cJSON_AddNumberToObject(cjson_data, "key-4-report", 1);
								}
								else
								{
									cJSON_AddNumberToObject(cjson_data, "key-4-report", 0);
								}
							}
						}

						pData = (uint8_t *)cJSON_Print(cjson_tx);
						dataLen = strlen((const char *)pData);
						sendBuf[sendLen++] = dataLen & 0xFF;
						sendBuf[sendLen++] = dataLen >> 8;
						memcpy(&sendBuf[sendLen], pData, dataLen);
						sendLen += dataLen;

						/* 回收堆空间 */
						cJSON_Delete(cjson_rx);
						cJSON_Delete(cjson_tx);
					}
					break;
				}
				sendBuf[sendLen++] = cal_crc_sum(sendBuf, sendLen);
				comm_send_bytes(sendBuf, sendLen);
			}
			/* mcu ota协议(字节流) */
			else if(type == 0xF0)
			{
				sendBuf[sendLen++] = 0xAA;
				sendBuf[sendLen++] = 0xBB;
				sendBuf[sendLen++] = 0xF0;
				sendBuf[sendLen++] = sn & 0xFF;
				sendBuf[sendLen++] = sn >> 8;
				/* 查询版本信息 */
				if(data[0] == 0x01)
				{
					sendBuf[sendLen++] = 0x04;
					sendBuf[sendLen++] = 0x00;
					sendBuf[sendLen++] = 0x02;
					sendBuf[sendLen++] = VERSION_MAJOR;
					sendBuf[sendLen++] = VERSION_MINOR;
					sendBuf[sendLen++] = VERSION_PATCH;
					sendBuf[sendLen++] = cal_crc_sum(sendBuf, sendLen);
					comm_send_bytes(sendBuf, sendLen);
				}
				/* 请求升级 */
				else if(data[0] == 0x03)
				{
					otaObj.fileSize = (data[1] << 24) | (data[2] << 16) | (data[3] << 8) | (data[4]);
					otaObj.blockSize = (data[5] << 24) | (data[6] << 16) | (data[7] << 8) | (data[8]);
					otaObj.verMajor = data[9];
					otaObj.verMinor = data[10];
					otaObj.verPatch = data[11];
					if(otaObj.verMajor != VERSION_MAJOR)
					{
						return;
					}
					if(otaObj.verMinor != VERSION_MINOR)
					{
						return;
					}
					if(otaObj.verPatch != VERSION_PATCH)
					{
						return;
					}
					if(otaObj.fileSize > PAGE_SIZE * DOWNLOAD_PAGE_NUM)
					{
						return;
					}
					for(uint16_t i = 0; i <= otaObj.fileSize / PAGE_SIZE; i++)
					{
						fmc_erase_page(DOWNLOAD_ADDR + PAGE_SIZE * i);
					}
					sendBuf[sendLen++] = 0x01;
					sendBuf[sendLen++] = 0x00;
					sendBuf[sendLen++] = 0x04;
					sendBuf[sendLen++] = cal_crc_sum(sendBuf, sendLen);
					comm_send_bytes(sendBuf, sendLen);
				}
				/* 传输固件包 */
				else if(data[0] == 0x05)
				{
					memcpy((OTAInfo *)&otaObj, &data[1], sizeof(OTAInfo));
					otaObj.info.dataLen = (data[9] << 8) | data[10];
					if(otaObj.info.magic[0] == 0xAA && otaObj.info.magic[1] == 0x55)
					{
						/* 固件包校验 */
						if(OTA_CRC16_GEN_Cal((uint8_t *)&data[5], dataLen - 5) == ((otaObj.info.crc[0] << 8) | otaObj.info.crc[1]))
						{
							/* 下载固件 */
							fmc_program(DOWNLOAD_ADDR + otaObj.receivedFileSize, (uint8_t *)(&data[1] + sizeof(OTAInfo)), otaObj.info.dataLen);
							otaObj.receivedFileSize += otaObj.info.dataLen;
							sendBuf[sendLen++] = 0x01;
							sendBuf[sendLen++] = 0x00;
							sendBuf[sendLen++] = 0x06;
							sendBuf[sendLen++] = cal_crc_sum(sendBuf, sendLen);
							comm_send_bytes(sendBuf, sendLen);

							/* 下载完成 */
							if(otaObj.receivedFileSize == otaObj.fileSize)
							{
								/* 更新bootloader标志位 */
								uint32_t key = UPDATE_KEY;
								fmc_erase_page(VERSION_INFO_ADDR);
								fmc_program(VERSION_INFO_FILESIZE_ADDR, (uint8_t *)&otaObj.fileSize, sizeof(otaObj.fileSize));
								fmc_program(VERSION_INFO_UPDATE_ADDR, (uint8_t *)&key, sizeof(key));
								/* 下载完成，灭灯1s后重启 */
								for(uint8_t i = 0; i < KEY_NUM; i++)
								{
									relay_set(i, 0);
									led_set(i, 0);
									led_set(i + 8, 0);
								}
								delay_ms(1000);
								/* 复位单片机 */
								NVIC_SystemReset();
							}
						}
						else
						{
							return;
						}
					}
				}
				
			}
		}
		/* crc校验失败 */
		else
		{

		}
	}
	/* 帧头不匹配 */
	else
	{

	}
}

void comm_receiver_process(void)
{
	if(comm.len != 0)
	{
		comm_receiver_callback(comm.buf, comm.len);
		
		comm.len = 0;
	}
}

void comm_send_factory(void)
{
	uint8_t  sendBuf[COMM_BUFFSIZE];
	uint16_t sendLen = 0;
	uint8_t  *pData;
	uint16_t dataLen;
	cJSON *cjson_tx = NULL;

	sendBuf[sendLen++] = 0xAA;
	sendBuf[sendLen++] = 0xBB;
	sendBuf[sendLen++] = 0x01;
	sendBuf[sendLen++] = 0x00;
	sendBuf[sendLen++] = 0x00;

	cjson_tx = cJSON_CreateObject();
	cJSON_AddStringToObject(cjson_tx, "cmd", "factory");
	pData = (uint8_t *)cJSON_Print(cjson_tx);
	dataLen = strlen((const char *)pData);
	sendBuf[sendLen++] = dataLen & 0xFF;
	sendBuf[sendLen++] = dataLen >> 8;
	memcpy(&sendBuf[sendLen], pData, dataLen);
	sendLen += dataLen;
	sendBuf[sendLen++] = cal_crc_sum(sendBuf, sendLen);
	comm_send_bytes(sendBuf, sendLen);
	/* 回收堆空间 */
	cJSON_Delete(cjson_tx);
	cJSON_free(pData);
}

void comm_send_key_state(uint8_t keyId, uint8_t State)
{
	uint8_t  sendBuf[COMM_BUFFSIZE];
	uint16_t sendLen = 0;
	uint8_t  *pData;
	uint16_t dataLen;
	cJSON *cjson_tx = NULL;
	cJSON *cjson_data = NULL;

	sendBuf[sendLen++] = 0xAA;
	sendBuf[sendLen++] = 0xBB;
	sendBuf[sendLen++] = 0x01;
	sendBuf[sendLen++] = 0x00;
	sendBuf[sendLen++] = 0x00;

	cjson_tx = cJSON_CreateObject();
	cjson_data = cJSON_CreateObject();
	if(keyxUpLoadEn[keyId] == 0)
	{
		cJSON_AddStringToObject(cjson_tx, "cmd", "status");
		cJSON_AddNumberToObject(cjson_tx, "aei", keyId + 1);
		cJSON_AddStringToObject(cjson_tx, "rsi", "_state");
		cJSON_AddItemToObject(cjson_tx, "data", cjson_data);
		if(State)
		{
			cJSON_AddStringToObject(cjson_data, "id", "_on");
			cJSON_AddStringToObject(cjson_data, "name", "switch");
			cJSON_AddStringToObject(cjson_data, "data", "1");
		}
		else
		{
			cJSON_AddStringToObject(cjson_data, "id", "_off");
			cJSON_AddStringToObject(cjson_data, "name", "switch");
			cJSON_AddStringToObject(cjson_data, "data", "0");
		}
	}
	else
	{
		cJSON_AddStringToObject(cjson_tx, "cmd", "status");
		cJSON_AddNumberToObject(cjson_tx, "aei", keyId + 1);
		cJSON_AddStringToObject(cjson_tx, "rsi", "_state");
		cJSON_AddItemToObject(cjson_tx, "data", cjson_data);
		cJSON_AddStringToObject(cjson_data, "id", "_keyType");
		cJSON_AddStringToObject(cjson_data, "name", "scene");
		cJSON_AddStringToObject(cjson_data, "data", "1");
	}
	pData = (uint8_t *)cJSON_Print(cjson_tx);
	dataLen = strlen((const char *)pData);
	sendBuf[sendLen++] = dataLen & 0xFF;
	sendBuf[sendLen++] = dataLen >> 8;
	memcpy(&sendBuf[sendLen], pData, dataLen);
	sendLen += dataLen;
	sendBuf[sendLen++] = cal_crc_sum(sendBuf, sendLen);
	comm_send_bytes(sendBuf, sendLen);
	/* 回收堆空间 */
	cJSON_Delete(cjson_tx);
	cJSON_free(pData);
}

static uint16_t OTA_CRC16_GEN_Cal(uint8_t *pData, uint16_t len)
{
	uint16_t crc;
	uint8_t temp;
	crc = 0x00;
	while (len-- != 0) {
		temp = (uint8_t)(crc / 256);
		crc <<= 8;
		crc ^= OTA_Crc16InitTable[temp ^ *pData];
		pData++;
	}
	return(crc);
}

void USART0_IRQHandler(void)	
{
	//空闲中断
    if(RESET != usart_interrupt_flag_get(USART0, USART_INT_FLAG_IDLE)) 
	{
		/* 清除空闲中断标志位 */
		usart_interrupt_flag_clear(USART0, USART_INT_FLAG_IDLE);	
		/* 清除接收完成标志位 */
		usart_data_receive(USART0);
		/* 关闭DMA传输 */
		dma_channel_disable(DMA0, DMA_CH4);
		
		comm.len = sizeof(dmaCh2Buf) - dma_transfer_number_get(DMA0, DMA_CH4);
		/* 转存数据到待处理数据缓冲区 */
		memcpy(comm.buf, dmaCh2Buf, comm.len);
		
		/* 重新设置DMA传输 */
		dma_memory_address_config(DMA0, DMA_CH4, (uint32_t)dmaCh2Buf);
		dma_transfer_number_config(DMA0, DMA_CH4, sizeof(dmaCh2Buf));
		/* 开启DMA传输 */
		dma_channel_enable(DMA0, DMA_CH4);
    }
}

